package 程序员面试金典;

import java.util.LinkedList;
import java.util.Stack;

public class StackOfPlates {

    int cap;
    LinkedList<Stack<Integer>> lists;
    public StackOfPlates(int cap) {
        this.cap=cap;
        this.lists=new LinkedList<>();
    }

    public void push(int val) {
         if (cap<=0)
             return;
         if (lists.isEmpty())
             lists.add(new Stack<Integer>());
         //最近一个栈满，则新加一个栈
         if (lists.get(lists.size()-1).size()>=cap){
             lists.add(new Stack<Integer>());
         }
         //取出最近的一个栈
         Stack<Integer> stack = lists.get(lists.size() - 1);
         stack.push(val);
    }

    public int pop() {
        if (lists.isEmpty())
            return -1;
        Stack<Integer> stack = lists.get(lists.size() - 1);
        Integer pop = stack.pop();
        if (stack.isEmpty())
            lists.removeLast();
        return pop;
    }

    public int popAt(int index) {
          if (index<0 || index>=lists.size())
              return -1;
        Stack<Integer> stack = lists.get(index);
        Integer pop = stack.pop();
        if (stack.isEmpty())
            lists.remove(index);
        return pop;
    }
}
